<template>
  <el-container v-loading="loading">
    <el-form label-width="80px" label-position="left" size="small">

      <el-form-item  label-width="0">
        <el-button type="primary" @click="openAddMapConfig">添加绘制点</el-button>
        <el-button type="primary" @click="editorMapConfig" v-if="!editorStatus">编辑所有坐标点</el-button>
        <el-button type="primary" @click="closeEditorMapConfig" v-if="editorStatus">结束编辑模式</el-button>
        <el-button type="danger" @click="clearMapConfig">清空地图中所有坐标点</el-button>
        <el-button type="success" @click="sendRequest">立即保存</el-button>
      </el-form-item>

      <el-form-item label="区域搜索" style="margin: 0" class="pull-right">
        <el-input v-model="addressSearchForm.keywords" placeholder="请输入需要搜索的位置">
          <el-button slot="prepend" icon="fa fa-fw fa-map-marker"></el-button>
          <el-button  slot="append" size="mini" icon="fa fa-fw fa-search" @click="searchKeywords()">搜索</el-button>
        </el-input>
      </el-form-item>


      <el-row>
        <div id="map-container" class="map-container"></div>
      </el-row>

    </el-form>

  </el-container>
</template>
<script>
  export default {
    methods: {
      goBack: function () {
        this.$router.go(-1)
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      openAddMapConfig: function () { // 添加坐标
        if(this.editorStatus){
          this.closeEditorMapConfig();
        }
        polygonDrawUtil.beginDraw();
      },
      editorMapConfig: function () {    // 编辑全部坐标
        let polygonGroup = polygonDrawUtil.getAllPolygon();
        for(let key in polygonGroup){
          polygonDrawUtil.polyEditor({map: map, PolygonObject: polygonGroup[key]});
        }
        this.editorStatus = true;
      },
      closeEditorMapConfig: function () {    // 结束编辑模式
        polygonDrawUtil.polyEditorSave();
        this.editorStatus = false;
      },
      clearMapConfig:function () {  // 清空地图中的配置
        let polygonGroup = polygonDrawUtil.getAllPolygon();
        for(let key in polygonGroup){
          polygonDrawUtil.polyDelete({map: map, PolygonObject: polygonGroup[key]});
        }
        this.editorStatus = true;
      },
      searchKeywords: function () {   // 关键字搜索
        let _this = this;
        let keywords = _this.addressSearchForm.keywords;
        // 关键字搜索
        AMap.service('AMap.PlaceSearch', function () {
          msearch = new AMap.PlaceSearch({
            map:map
          });
          msearch.search(keywords, function (status, result) {
            let poiList = result.poiList;
            if (poiList.count > 0) {
              let poi = poiList.pois[0].location;
              mapContainer.setCenter(poi);
              mapContainer.setZoom(16);
              _this.addressSearchForm.location = poi;
            }
          })
        });
      },
      sendRequest: function () {  // 发送提交请求
        let _this = this;
        let polygonGroup = polygonDrawUtil.getAllPolygon();
        let pathGroup = [],tempPath = null,tempPolygon = null;
        for(let key in polygonGroup){
          tempPath = [];
          tempPolygon = polygonDrawUtil.polyGetPath({PolygonObject: polygonGroup[key]});
          for(let childrenKey in tempPolygon){
            tempPath.push({
              x: tempPolygon[childrenKey].O,
              y: tempPolygon[childrenKey].P
            })
          }
          pathGroup.push(tempPath);
        }
        _this.api.updateTerritorialRestriction({
          area: JSON.stringify(pathGroup)
        }).then(function (res) {
          if (res.code == 1) {
            _this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
            });
          } else {
            _this.$message({
              showClose: true,
              message: res.msg,
              type: 'warning'
            });
          }
        }).catch(function (error) {
          throw new Error(error);
        });
      }
    },
    data() {
      return {
        loading: true,  // 页面加载
        editorStatus: false,  // 编辑状态
        addressSearchForm: {
          keywords: '',
          location: null,
        },
        windowAlert: {
          hintText: '',
          isShow: false,
          defaultTimeOut: 2000
        },
      }
    },
    mounted: function () {
      let _this = this;
      // 地图一
      map = new AMap.Map("map-container", {
        resizeEnable: true,
        // center: [116.403322, 39.900255],//地图中心点
        // zoom: 15 //地图显示的缩放级别
      });

      //在地图中添加MouseTool插件
      AMap.service('AMap.MouseTool', function () {
        mouseTool = new AMap.MouseTool(map);
      });

      /**
       * 双击结束绘制
       * */
      map.on('dblclick', function () {
        if (polygonDrawUtil.drawStatus) {
          polygonDrawUtil.getCurrentPolygonDraw();
          polygonDrawUtil.drawStatus = false;
        }
      })

      polygonConfig = {
        map: map
      }

      polygonDrawUtil = new PolygonDrawUtil({mouseTool: mouseTool, polygonConfig: polygonConfig});

      this.api.getTerritorialRestriction().then(function (res) {
        if (res.code == 1) {
          polygonDrawUtil.addPolygonByPathGroup({map: map, PathGroup: res.data});
        }
        _this.loading = false;
      }).catch(function (res) {
        throw new Error(res);
      });
    }
  }


  let map;
  let mouseTool;  // 工具句柄
  let polygonDrawUtil;  // 工具


  let mapContainer;
  let toolBar;
  let msearch;


  // 配置参数
  let polygonConfig;

  /*
   * 多边形绘制工具
   * @auth MrNan
   */
  class PolygonDrawUtil {
    /**
     * @param mouseTool 工具句柄
     * @param polygonConfig 绘制配置文件
     */
    constructor({mouseTool: mouseTool, polygonConfig: polygonConfig}) {
      this.mouseTool = mouseTool;
      this.polygonConfig = polygonConfig;
      this.tempPolygon = null;
      this.beforeSize = 0;
      this.currentSize = 0;
      this.drawStatus = false;
      this.editorPolylineGroup = [];  // 编辑状态数组
    }

    /**
     * 绘制
     */
    beginDraw() {
      this.mouseTool.polygon(this.polygonConfig);
      this.tempPolygon = null;
      this.drawStatus = true;
    }

    /**
     * 结束编辑并返回当前的绘制的多边形
     * @param map
     */
    getCurrentPolygonDraw() {
      this.mouseTool.close(false);
      let arr = this.polygonConfig.map.getAllOverlays();
      this.currentSize = arr.length;
      if (this.currentSize > this.beforeSize) {
        this.beforeSize = this.currentSize;
        this.tempPolygon = arr[this.currentSize - 1];
      }
    }

    /**
     * 获取地图中的所有坐标
     * */
    getAllPolygon(){
      return this.polygonConfig.map.getAllOverlays();
    }

    /**
     * 结束编辑,并清除绘制
     * */
    closeDrawSlsoClear() {
      this.getCurrentPolygonDraw();
      if (this.tempPolygon) {
        this.polyDelete({PolygonObject: this.tempPolygon});
      }
    }

    /**
     * 开启折线的编辑状态
     * @param PolygonObject
     */
    polyEditor({map: map, PolygonObject: PolygonObject}) {
      let _this = this;
      map.plugin(["AMap.PolyEditor"], function () {
        let polylineEditor = new AMap.PolyEditor(map, PolygonObject);
        polylineEditor.open();
        _this.editorPolylineGroup.push(polylineEditor);
      });
    }

    /**
     * 关闭折线的编辑状态
     * @param PolygonObject
     */
    polyEditorSave() {
      for(let key in this.editorPolylineGroup){
        this.editorPolylineGroup[key].close();
      }
      this.editorPolylineGroup = [];
    }

    /**
     * 删除折线覆盖物
     */
    polyDelete({PolygonObject: PolygonObject}) {
      this.polygonConfig.map.remove(PolygonObject);
    }

    /**
     * 获取折线对象路径信息
     */
    polyGetPath({PolygonObject: polygonObject}) {
      return polygonObject.getPath();
    }
    /**
     * 添加标记,并锁定中心区域为位置对象的坐标点区域
     */
    addMarker({map: map, icon: icon, location: location}) {
      let marker = new AMap.Marker({
        position: new AMap.LngLat(location.O, location.P),
        icon: icon
      });
      map.clearMap();
      map.add(marker);
      map.setCenter(location);
      map.setZoom(18);
    }

    /**
     * 添加多边形
     * @param map 地图对象
     * @param polygonGroup 多边形数组
     */
    addPolygonByPolygonGroup({map: map, PolygonGroup: polygonGroup}){
      if(polygonGroup.length <= 0){
        return false;
      }
      for(let key in polygonGroup){
        map.add(polygonGroup[key]);
      }
    }

    /**
     * 添加多边形
     * @param map 地图对象
     * @param pathGroup 路径数组
     */
    addPolygonByPathGroup({map: map, PathGroup: pathGroup}){
      if(pathGroup.length <= 0){
        return false;
      }
      let latGroup = null;
      for(let key in pathGroup){
        latGroup = [];
        for(let childrenKey in pathGroup[key]){
          latGroup.push(new AMap.LngLat(pathGroup[key][childrenKey].x,pathGroup[key][childrenKey].y));
        }
        map.add(new AMap.Polygon({
          path: latGroup,
          fillColor: 'rgba(55,159,249,.5)', // 多边形填充颜色
          borderWeight: 1, // 线条宽度，默认为 1
          strokeColor: 'rgba(55,159,249,1)', // 线条颜色
        }));
      }
    }
  }


</script>

<style scoped>
  .el-container {
    display: block;
  }

  .el-form {
    margin: 15px 30px;
  }
  .el-form-item{
    display: inline-block;
  }

  .map-container {
    width: 100%;
    height: 750px;
  }


</style>
